package com.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.ReferenceCountUtil;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * @author xurongbei
 */
public class NettyClient2 {

    private EventLoopGroup group = null;

    private Bootstrap bootstrap = null;

    public NettyClient2() {
        init();
    }

    private void init(){
        group=new NioEventLoopGroup();
        bootstrap=new Bootstrap();
        bootstrap.group(group);
        bootstrap.channel(NioSocketChannel.class);
        System.out.println("1111111");
    }

    public ChannelFuture doRequest(String host, int port, final ChannelHandler... handlers) throws InterruptedException
    {
        System.out.println("进入doRequest！");
        this.bootstrap.handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(handlers);

            }
        });
        ChannelFuture future=this.bootstrap.connect(host,port).sync();
        return future;
    }
    public void release(){
        this.group.shutdownGracefully();
    }

    public static void main(String[] args) {
        NettyClient2 client=null;
        ChannelFuture future=null;
        try{
            client=new NettyClient2();
            future=client.doRequest("localhost", 9999, new ChannelInboundHandlerAdapter(){
                @Override
                public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                    try{
                        ByteBuf readBuffer=(ByteBuf)msg;
                        byte[] tempDatas=new byte[readBuffer.readableBytes()];
                        readBuffer.readBytes(tempDatas);
                        System.out.println("from server:"+new String(tempDatas,"UTF-8"));
                        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
                        String line=br.readLine();
                        ctx.writeAndFlush(Unpooled.copiedBuffer(line.getBytes("UTF-8")));

                    }
                    finally{
                        ReferenceCountUtil.release(msg);
                    }
                }

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                    System.out.println("client exceptionCanght method run...");
                    ctx.close();
                }
            });
            //Scanner s=null;
            future.channel().writeAndFlush(Unpooled.copiedBuffer("连接成功".getBytes("UTF-8")));
            //future.channel().writeAndFlush(Unpooled.copiedBuffer(line.getBytes("UTF-8")));
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            if(null!=future)
            {
                try{
                    future.channel().closeFuture().sync();
                }catch(InterruptedException e){
                    e.printStackTrace();
                }
            }
            if(null != client)
            {
                client.release();
            }
        }
    }

}
